package handlers

import (
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"supply-chain/models"
)

type SupplierHandler struct {
	DB *gorm.DB
}

type MaterialInput struct {
	EPCID string `json:"epc_id" binding:"required"`
	Name  string `json:"name" binding:"required"`
}

// CheckInMaterial 处理原材料入库
func (h *SupplierHandler) CheckInMaterial(c *gin.Context) {
	var input MaterialInput
	if err := c.ShouldBindJSON(&input); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	material := models.Material{
		EPCID:       input.EPCID,
		Name:        input.Name,
		CheckInTime: time.Now(),
		Trans:       "supplier",
		Status:      "in_stock",
	}

	if err := h.DB.Create(&material).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to store material"})
		return
	}

	c.JSON(http.StatusOK, material)
}

// GetMaterial 获取原材料信息
func (h *SupplierHandler) GetMaterial(c *gin.Context) {
	epcID := c.Param("epc_id")
	var material models.Material

	if err := h.DB.Where("epc_id = ?", epcID).First(&material).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "Material not found"})
		return
	}

	c.JSON(http.StatusOK, material)
}